/**
 * Title :		Hyperbolic tree engine
 * Description: jFamilyTree Engine
 * Version:		1.10.x
 * Copyright:	(c) 2001-2005
 * Terms of use:see license agreement at http://treebolic.sourceforge.net/en/license.htm
 * Author:		Bernard Bou
 * Company:		bsys
 * Update:		19 juil. 2008
 */

package jFamilyTree.model.graph;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import jFamilyTree.model.IEdge;
import jFamilyTree.model.INode;
import jFamilyTree.model.MutableEdge;
import jFamilyTree.model.Tree;
import jFamilyTree.model.TreeMutableNode;

/**
 * Graph converter
 * 
 * @author Bernard Bou
 */
public class Converter<T extends TreeMutableNode>
{
	/**
	 * Convert graph to tree
	 * 
	 * @param thisGraph
	 * @return tree
	 */
	@SuppressWarnings( { "unchecked" })
	public Tree graphToTree(jFamilyTree.model.graph.Graph thisGraph)
	{
		jFamilyTree.model.graph.Tree thisSpanningTree = thisGraph.makeSpanningTree();

		// tree edges
		Collection<GraphEdge> theseGraphEdges = thisSpanningTree.theGraph.getEdges();
		for (GraphEdge thisGraphEdge : theseGraphEdges)
		{
			T thisFromNode = (T) thisGraphEdge.getFrom();
			T thisToNode = (T) thisGraphEdge.getTo();
			thisToNode.addToParent(thisFromNode);

			// transfer style
			IEdge thisEdge = (IEdge) thisGraphEdge.getUserData();
			thisToNode.setEdgeColor(thisEdge.getColor());
			thisToNode.setEdgeStyle(thisEdge.getStyle());
			thisToNode.setEdgeLabel(thisEdge.getLabel());
			thisToNode.setEdgeImageFile(thisEdge.getImageFile());
		}

		// non-tree edges
		List<IEdge> theseEdges = null;
		for (GraphEdge thisGraphEdge : thisGraph.getEdges())
		{
			if (theseGraphEdges.contains(thisGraphEdge))
				continue;
			MutableEdge thisEdge = (MutableEdge) thisGraphEdge.getUserData();
			if (theseEdges == null)
				theseEdges = new ArrayList<IEdge>();
			theseEdges.add(thisEdge);
		}

		return new Tree((INode) thisSpanningTree.theRoot, theseEdges);
	}
}
